package com.woniu.product.listener;

import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.woniu.common.dto.SkuOrderDto;
import com.woniu.common.dto.SkuOrderJifenDto;
import com.woniu.product.service.TOrderService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.woniu.common.constant.MqConstant.Queue.*;

/**
 * @author sw
 * @Description
 * @Date 2024/5/28 18:21
 */
@Component
@Slf4j
public class JifenSkuOrderListener {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TOrderService orderService;

    @RabbitListener(queues = SKU_JIFEN_ORDER_QUEUE)
    @SneakyThrows
    public void addSkuOrder(String msg, Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String messageId = message.getMessageProperties().getMessageId();
        try {
            Boolean delete = redisTemplate.delete("message:" + messageId);
            if (delete) {
                JSONObject jsonObject = JSONObject.parseObject(msg, JSONObject.class);
                //把参数拿出来
                SkuOrderJifenDto skuOrderDto = jsonObject.getObject("skuOrderDto", SkuOrderJifenDto.class);

                Long orderNum = jsonObject.getLong("orderId");

                //处理业务，下单：生产订单数据
                orderService.addJifenSkuOrder(skuOrderDto,orderNum);
            }
            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            log.error("addSkuOrder error:{}",e);
            redisTemplate.opsForValue().set(messageId,messageId,30, TimeUnit.MINUTES);
            // 拒绝签收并不保留消息,直接到死信
            channel.basicReject(deliveryTag,false);
        }

    }

    @RabbitListener(queues = DLX_TTL_SKU_JIFEN_ORDER_QUEUE)
    @SneakyThrows
    public void rollbackJifenSkuOrder(String msg, Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            JSONObject jsonObject = JSONObject.parseObject(msg, JSONObject.class);
            //把参数拿出来
            SkuOrderDto skuOrderDto = jsonObject.getObject("skuOrderDto", SkuOrderDto.class);

            Long orderNum = jsonObject.getLong("orderId");
            //处理业务,回滚订单
            orderService.rollbackJifenSkuOrder(skuOrderDto,orderNum);

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("rollbackSkuOrder error:{}",e);
            // 拒绝签收并不保留消息,直接到死信
            channel.basicReject(deliveryTag,false);
        }

    }

}
